package com.xinyiweidai.xinyiweidai.module.loan;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.google.gson.Gson;
import com.lan.mylibrary.okhttp.L;
import com.lan.mylibrary.okhttp.OkHttpUtils;
import com.lan.mylibrary.okhttp.callback.StringCallback;
import com.lan.mylibrary.ui.MyTitle;
import com.lan.mylibrary.ui.MyToast;
import com.xinyiweidai.xinyiweidai.R;
import com.xinyiweidai.xinyiweidai.base.BaseActivity;
import com.xinyiweidai.xinyiweidai.bean.AuthResult;
import com.xinyiweidai.xinyiweidai.bean.PayResult;
import com.xinyiweidai.xinyiweidai.bean.PaymentBean;
import com.xinyiweidai.xinyiweidai.bean.PaymentInfoBean;
import com.xinyiweidai.xinyiweidai.module.bind.CardActivity;
import com.xinyiweidai.xinyiweidai.module.login.LoginActivity;
import com.xinyiweidai.xinyiweidai.util.Api;
import com.xinyiweidai.xinyiweidai.util.SpUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Request;

public class PaymentActivity extends BaseActivity {


    private TextView tv_pay_all;
    private TextView tv_pay_time;
    private TextView tv_pay_overTime;
    private TextView tv_money;
    private TextView tv_lixi;
    private TextView tv_zhinajin;
    private TextView tv_money_type;
    private Button btn_payment;
    private RadioButton radio_payNow;
    private RadioButton radio_payWait;
    private LinearLayout ll_zhinajin;

    private int paytype=0;
    private String delaytime, payment_time;
    private double lixi, zhinajin, applyMoney, chargeMoney, allMoney;

    private static final int SDK_PAY_FLAG = 1001;
    private static final int SDK_AUTH_FLAG = 1002;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_payment;
    }


    @Override
    protected void initToolBar() {
        new MyTitle(this, R.drawable.ic_back, "申请还款", 0, true);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_pay_all = (TextView) findViewById(R.id.tv_pay_all);
        tv_pay_time = (TextView) findViewById(R.id.tv_pay_time);
        tv_pay_overTime = (TextView) findViewById(R.id.tv_pay_overTime);
        tv_money = (TextView) findViewById(R.id.tv_money);
        tv_lixi = (TextView) findViewById(R.id.tv_lixi);
        tv_zhinajin = (TextView) findViewById(R.id.tv_zhinajin);
        tv_money_type = (TextView) findViewById(R.id.tv_money_type);
        btn_payment = (Button) findViewById(R.id.btn_payment);
        radio_payNow = (RadioButton) findViewById(R.id.radio_payNow);
        radio_payWait = (RadioButton) findViewById(R.id.radio_payWait);
        ll_zhinajin = (LinearLayout) findViewById(R.id.ll_zhinajin);


        Map<String, String> map = new HashMap<>();
        map.put("token", SpUtil.getInstance().getUserInfo().getToken());
        getPaymentInfo(map);
    }


    private void getPaymentInfo(Map<String, String> map) {
        showLoading("正在加载");
        OkHttpUtils.get().url(Api.paymentInfo).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                dismissLoading();
                MyToast.showError(PaymentActivity.this, "网络异常");
            }

            @Override
            public void onResponse(String response) {
                L.e(response);
                dismissLoading();
                parseData(response);
            }
        });
    }


    private void parseData(String response) {
        PaymentInfoBean bean = new Gson().fromJson(response, PaymentInfoBean.class);
        if (bean.getCode() == 1) {
            initData(bean);
        } else {
            MyToast.showError(PaymentActivity.this, bean.getMessage());
        }
    }

    private void initData(PaymentInfoBean bean) {
        //还款时间
        delaytime = bean.getData().getApplyDay();
        //借款金额
        applyMoney = bean.getData().getApplyMoney();
        //利息
        lixi = bean.getData().getRateFee();
        //手续费
        chargeMoney = bean.getData().getChargeMoney();
        //还款日
        payment_time = bean.getData().getBackTime();
        //滞纳金
        zhinajin = bean.getData().getTotelfine();
        //还款总金额


        if (bean.getData().getYqts() > 0) {
            MyToast.showSuccess(this,"您已逾期\n无法延期还款");
            paytype=0;
            allMoney = applyMoney + lixi + zhinajin;
            radio_payWait.setVisibility(View.GONE);

            tv_pay_overTime.setVisibility(View.VISIBLE);
            tv_pay_overTime.setText("逾期天数： " + bean.getData().getYqts() + " 天");
            ll_zhinajin.setVisibility(View.VISIBLE);
            tv_zhinajin.setText(zhinajin + "");

            tv_pay_all.setText(allMoney + "");
            tv_pay_time.setText("还款时间： " + payment_time);
            tv_money_type.setText("借款金额");
            tv_money.setText(applyMoney + "");
            tv_lixi.setText(lixi + "");

        } else {
            paytype=0;
            allMoney = applyMoney + lixi;
            radio_payWait.setVisibility(View.VISIBLE);
            tv_pay_overTime.setVisibility(View.GONE);
            ll_zhinajin.setVisibility(View.GONE);

            tv_pay_all.setText(allMoney + "");
            tv_pay_time.setText("还款时间： " + payment_time);
            tv_money_type.setText("借款金额");
            tv_money.setText(applyMoney + "");
            tv_lixi.setText(lixi + "");
        }

        radio_payNow.setClickable(bean.getData().getYqts() <= 0);
    }


    @Override
    protected void addClickEvent() {
        radio_payNow.setOnCheckedChangeListener((compoundButton, checked) -> {
            paytype=0;
            allMoney = applyMoney + lixi;

            tv_pay_all.setText(allMoney + "");
            tv_pay_time.setText("还款时间： " + payment_time);
            tv_money_type.setText("借款金额");
            tv_money.setText(applyMoney + "");
            tv_lixi.setText(lixi + "");

        });
        radio_payWait.setOnClickListener(view -> {
            paytype=1;
            allMoney = chargeMoney + lixi;

            tv_pay_all.setText(allMoney + "");
            tv_pay_time.setText("还款时间： " + payment_time);
            tv_money_type.setText("系统升级费");
            tv_money.setText(chargeMoney + "");
            tv_lixi.setText(lixi + "");
        });
        btn_payment.setOnClickListener(view -> checkPay());
    }

    private void checkPay() {

        Map<String, String> map = new HashMap<>();
        map.put("amount", String.valueOf(allMoney));
        map.put("paytype", String.valueOf(paytype));
        map.put("delaytime", delaytime);
        map.put("token", SpUtil.getInstance().getUserInfo().getToken());
        map.put("userid", SpUtil.getInstance().getUserInfo().getUser_id());
        showLoading("正在加载");
        OkHttpUtils.post()
                .url(Api.payment)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        dismissLoading();
                        MyToast.showError(PaymentActivity.this, "网络异常");
                    }

                    @Override
                    public void onResponse(String response) {
                        L.e(response);
                        dismissLoading();
                        PaymentBean bean=new Gson().fromJson(response, PaymentBean.class);
                        goAlipay(bean.getData());
                    }
                });
    }


    private void goAlipay(String data) {
        Runnable authRunnable = () -> {
            AuthTask authTask = new AuthTask(PaymentActivity.this);
            Map<String, String> result = authTask.authV2(data, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(PaymentActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        PaymentActivity.this.finish();
                    } else {
                        Toast.makeText(PaymentActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    break;
                }
                default:
                    break;
            }
        }
    };
}
